package com.bantang.controller;


import com.bantang.JavaDockerCodeSandbox;
import com.bantang.model.SandBoxParam;
import com.bantang.model.SandBoxVO;
import com.bantang.template.CodeSandBoxTemplate;
import com.bantang.template.DockerSandBoxTemplate;
import com.bantang.template.JavaSandBoxTemplate;
import com.bantang.utils.CodeException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 代码沙箱
 */
@Controller
@ResponseBody
@RequestMapping("/")
public class CodeSandboxController {

    private static final String AUTH_REQUEST_HEADER = "auth";
    private static final String AUTH_REQUEST_SECRET = "secretKey";

    /**
     * java原生代码沙箱
     * @param sandBoxParam
     * @param request
     * @return
     */
    @PostMapping("/executeCode")
    public SandBoxVO codeSandBox(@RequestBody SandBoxParam sandBoxParam, HttpServletRequest request){

        String value = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(value)){
            throw new CodeException("参数异常");
        }

        CodeSandBoxTemplate codeSandBoxTemplate = new JavaSandBoxTemplate();
        return codeSandBoxTemplate.exec(sandBoxParam);
    }



    /**
     * docker实现代码沙箱
     * @param sandBoxParam
     * @param request
     * @return
     */
    @PostMapping("/executeCodeD")
    public SandBoxVO codeSandBoxD(@RequestBody SandBoxParam sandBoxParam, HttpServletRequest request){

        String value = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(value)){
            throw new CodeException("参数异常");
        }

        CodeSandBoxTemplate codeSandBoxTemplate = new DockerSandBoxTemplate();
        return codeSandBoxTemplate.exec(sandBoxParam);
    }


    /**
     * docker实现代码沙箱
     * @param sandBoxParam
     * @param request
     * @return
     */
    @PostMapping("/executeCodeDD")
    public SandBoxVO codeSandBoxDD(@RequestBody SandBoxParam sandBoxParam, HttpServletRequest request){

        String value = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(value)){
            throw new CodeException("参数异常");
        }

        JavaDockerCodeSandbox codeSandBoxTemplate = new JavaDockerCodeSandbox();
        return codeSandBoxTemplate.executeCodeSandBox(sandBoxParam);
    }

    @GetMapping("/hello")
    public String getSuccess(){
        return "word";
    }
}
